package initialize

import (
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"sale_system/inventory_srv/global"
	"sale_system/inventory_srv/model"
	"time"
)

func InitDB() {

	// 启动mysql
	user := global.ServerConfig.MysqlInfo.User
	password := global.ServerConfig.MysqlInfo.Password
	host := global.ServerConfig.MysqlInfo.Host
	port := global.ServerConfig.MysqlInfo.Port
	db := global.ServerConfig.MysqlInfo.DataBase

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		user, password, host, port, db)
	zap.S().Info(dsn)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		})

	var err error
	// 配置到全局global.DB
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: newLogger,
	})

	if err != nil {
		panic("failed to connect database")
	}

	// 自动迁移数据库表结构
	err = global.DB.AutoMigrate(
		&model.Inventory{},
		&model.StockSellDetail{},
		&model.TccTransaction{},
		&model.PreDeductInventory{},
	)
	if err != nil {
		panic(err)
	}

	// 如果Freeze字段不存在，手动添加
	if !global.DB.Migrator().HasColumn(&model.Inventory{}, "freeze") {
		err = global.DB.Exec("ALTER TABLE inventory ADD COLUMN freeze INT DEFAULT 0").Error
		if err != nil {
			panic(err)
		}
	}
}
